﻿@using Microsoft.AspNetCore.Mvc.ModelBinding

@model ImportProfileModel

@{
    var keyFieldNames = (List<SelectListItem>)ViewBag.KeyFieldNames;
    var hasIdKeyField = Model?.KeyFieldNames?.Contains("Id", StringComparer.OrdinalIgnoreCase) ?? false;
}

<div asp-validation-summary="ModelOnly"></div>
<input type="hidden" asp-for="Id" />
<input type="hidden" asp-for="EntityType" />

<script sm-target-zone="scripts" data-origin="ImportUpdate">
	window['onUploadCompleted'] = function (file, response) {
		if (response.success) {
			location.reload();
		}
		else if (!_.isEmpty(response.error)) {
			displayNotification(response.error, 'error');
        }
	}
</script>

<div sm-if="Model.ExistingFiles.Count(x => !x.RelatedType.HasValue) > 1" class="alert alert-warning">
	@T("Admin.DataExchange.Import.MultipleFilesSameFileTypeNote")
</div>
<div>
	<div class="adminContent">
        <div id="ImportFileUploadContainer" class="adminRow">
            <div class="adminTitle">
                &nbsp;
            </div>
            <div class="adminData">
				<file-uploader 
					file-uploader-name="ImportFileUploader"
					upload-url='@Url.Action("FileUpload", new { id = Model.Id })'
					type-filter=".csv,.xlsx,.txt,.tab"
					display-browse-media-button="false"
					display-remove-button="false"
					display-remove-button-after-upload="true"
					upload-text='@T(Model.ExistingFiles.Any() ? "Admin.DataExchange.Import.AddAnotherFile" : "Admin.DataExchange.Import.FileUpload")'
					onuploadcompleted="onUploadCompleted" />
            </div>
        </div>
        <div id="ImportFileListContainer" class="adminRow" attr-class='(!Model.ExistingFiles.Any(), "d-none")'>
            <div class="adminTitle">
                &nbsp;
            </div>
            <div id="ImportFileList" class="adminData wide">
                <div class="w-50">
                    @foreach (var file in Model.ExistingFiles)
                    {
                        var hasLabel = file.Label.HasValue();
                        <div class="py-2 border-bottom form-row">
                            <div class="col d-flex align-items-center">
                                <file-icon file-extension="@file.File.Extension" 
                                    show-label="@hasLabel"
                                    label="@file.Label"
                                    badge-class="@(hasLabel ? "badge-info" : null)" />
				                <a asp-action="DownloadImportFile" asp-route-id="@Model.Id" asp-route-name="@file.File.Name" class="pl-1" download>
					                @file.File.Name
				                </a>
                            </div>
							<div class="col-auto">
								<button type="button" 
                                    class="btn btn-secondary btn-to-danger btn-sm import-file-delete ml-3" 
                                    data-url="@Url.Action("DeleteImportFile", new { id = Model.Id, name = file.File.Name })">
									    <i class="far fa-trash-alt"></i>
									    <span>@T("Admin.Common.Delete")</span>
								</button>
							</div>
                        </div>
                    }
                </div>
            </div>
        </div>
        <div sm-if="Model.TaskId > 0" class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="TaskId" />
            </div>
            <div class="adminData">
                @await Component.InvokeAsync("MinimalTask", new { taskId = Model.TaskId, returnUrl = Context.Request.RawUrl(), reloadPage = true })
            </div>
        </div>
        <div sm-if="Model.ImportResult != null" class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="ImportResult" />
            </div>
            <div class="adminData">
                <partial name="ProfileImportResult" model="Model.ImportResult" />
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="FolderName" />
            </div>
            <div class="adminData">
				<div class="form-control-plaintext">
					@Model.FolderName.NaIfEmpty()
				</div>
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="EntityTypeName" />
            </div>
            <div class="adminData">
                <input asp-for="EntityTypeName" sm-plaintext="true" readonly />
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="Enabled" />
            </div>
            <div class="adminData">
                <input asp-for="Enabled" />
                <span asp-validation-for="Enabled"></span>
            </div>
        </div>
        <div sm-if="Model.EntityType == ImportEntityType.Product" class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="ImportRelatedData" />
            </div>
            <div class="adminData">
                <input asp-for="ImportRelatedData" />
                <span asp-validation-for="ImportRelatedData"></span>
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="Name" />
            </div>
            <div class="adminData">
                <input asp-for="Name" />
                <span asp-validation-for="Name"></span>
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="KeyFieldNames" />
            </div>
            <div class="adminData">
                @*Special case where the user must be able to change the stored order.*@
                <select asp-for="KeyFieldNames" multiple="multiple">
					@foreach (var field in Model.KeyFieldNames)
					{
						var availableKey = keyFieldNames.FirstOrDefault(x => x.Value == field);
						<option value="@field" selected="selected">@(availableKey != null ? availableKey.Text : field)</option>
					}
					@foreach (var field in keyFieldNames)
					{
						var selectedKey = Model.KeyFieldNames.FirstOrDefault(x => x == field.Value);
						if (!selectedKey.HasValue())
						{
							<option value="@field.Value">@field.Text</option>
						}
					}
                </select>
                <span asp-validation-for="KeyFieldNames"></span>
            </div>
        </div>
        <div sm-if="hasIdKeyField" class="adminRow">
			<div class="alert alert-warning">
				@T("Admin.DataExchange.Import.KeyFieldNames.Note")
			</div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="Skip" />
            </div>
            <div class="adminData">
                <editor asp-for="Skip" />
                <span asp-validation-for="Skip"></span>
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="Take" />
            </div>
            <div class="adminData">
                <editor asp-for="Take" />
                <span asp-validation-for="Take"></span>
            </div>
        </div>
        <div class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="UpdateOnly" />
            </div>
            <div class="adminData">
                <input asp-for="UpdateOnly" />
                <span asp-validation-for="UpdateOnly"></span>
            </div>
        </div>
        <div sm-if="Model.EntityType == ImportEntityType.Product" class="adminRow">
            <div class="adminTitle">
                <smart-label asp-for="ExtraData.NumberOfPictures" />
            </div>
            <div class="adminData">
                <editor asp-for="ExtraData.NumberOfPictures" />
                <span asp-validation-for="ExtraData.NumberOfPictures"></span>
            </div>
        </div>
	</div>
</div>

@if (Model.FileType == ImportFileType.Csv)
{
    var configViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
	configViewData["ShowGroupCaption"] = true;
	configViewData.TemplateInfo.HtmlFieldPrefix = "CsvConfiguration";
	configViewData.ModelState.Merge(ViewData.ModelState);

    <partial name="_CsvConfiguration" model="Model.CsvConfiguration" view-data="configViewData" />
}

@if (Model.ExistingFiles.Any(x => !x.RelatedType.HasValue))
{
    <partial name="_ColumnMappings" model="Model" />
}

<script sm-target-zone="scripts" data-origin="ImportUpdate">
    var mappedProperties = [];

    $(function() {
        const maxMappingLableLength = 42;
        var askToProceed = @T("Admin.Common.AskToProceed").JsValue;
        var mappings = $('#ImportColumnMappings');

		// Delete import file.
		$('#ImportFileList').on('click', '.import-file-delete', function (e) {
            e.preventDefault();
            $(this).postData({
                ask: askToProceed
			});
			return false;
		});

		// Execute import.
        $('#ProfileImportButton').on('click', function (e) {
			e.preventDefault();
            $(this).postData({
                ask: askToProceed
			});
			return false;
		});

        // BEGIN column mapping.
		// Reset column mappings.
		$('#ResetColumnMappings').on('click', function (e) {
			e.preventDefault();

            confirm2({
                message: askToProceed,
                icon: { type: 'warning' },
                callback: accepted => {
					if (accepted) {
						var form = '<form id="ResetColumnMappingsForm" action="' + $(this).data('url') + '" method="post">';
						form += '<input type="hidden" name="__RequestVerificationToken" value="@Html.GetAntiforgeryToken()">';
                        form += '</form>';
				        $('body').append(form);
				        $('#ResetColumnMappingsForm').submit();
                    }
                }
            });
			return false;
		});

		// Mapping row handling.
		mappings.on('change', '.select-property, .select-column', function (e) {
			e.stopPropagation();
			var row = $(this).closest('tr');
			if (row.hasClass('column-mapping-new')) {
				var properties = row.find('.select-property');
				var hasColumn = !_.isEmpty(row.find('.select-column').select2('val'));
                var hasProperty = !_.isEmpty(properties.select2('val'));
				var isDefaultDisabled = (properties.find('option:selected').attr('data-defaultdisabled') === '1');

				row.find('.input-default').prop('disabled', !hasColumn || isDefaultDisabled);
				row.find('.mapping-add').prop('disabled', !(hasProperty && hasColumn));
			}
		});

        // Start editing mapping item.
        mappings.on('click', '.item-inner', function (e) {
			e.stopPropagation();
			var item = $(this).closest('.mapping-item');

			closeAllMappingEdits();

			if (item.find('select').length > 0)
				return;

			var isProperty = item.hasClass('mapping-property');
			var template = $(isProperty ? '#PropertyMappingTemplate' : '#ColumnMappingTemplate').children(':first');
			var currentValue = item.find(isProperty ? 'input[name^="ColumnMapping.Property."]' : 'input[name^="ColumnMapping.Column."]').val();

			// Hide static label.
			item.find('.item-inner').hide();

			// Clone edit template into mapping item.
			var select = template.clone().appendTo(item).find('select');
			select.val(currentValue);

			select = initSelectBox(select, isProperty);
			select.select2('focus');
		});

        // Apply edited values.
        mappings.on('click', '.mapping-apply', function (e) {
			e.stopPropagation();
			var item = $(this).closest('.mapping-item');
			var val = item.find('select').select2('val');

			item.find('input[type=hidden]').val(val);

			if (item.hasClass('mapping-property')) {
				updatePropertyLabel(item, val);
			}
			else {
				if (_.isEmpty(val)) {
					val = '<span class="muted">' + @T("Admin.Common.Ignore").JsValue + '</span>';
				}
				item.find('.left-label').html(val);
			}

			var row = $(this).closest('tr');
			var hasColumn = !_.isEmpty(row.find('input[name^="ColumnMapping.Column."]').val());
			var property = row.find('input[name^="ColumnMapping.Property."]').val();
			var properties = $('#PropertyMappingTemplate').find('select');
			var isDefaultDisabled = (properties.find('option[value="' + property + '"]').attr('data-defaultdisabled') === '1');

			row.find('.input-default').prop('disabled', !hasColumn || isDefaultDisabled);

			closeAllMappingEdits();
		});

	    // Add new mapping row.
        mappings.on('click', '.mapping-add', function (e) {
			e.stopPropagation();
			var row = $(this).closest('tr');
			var table = row.closest('table');
			var index = parseInt(table.attr('data-maxindex')) + 1;

			var property = row.find('.select-property').select2('val');
			var column = row.find('.select-column').select2('val');

			row.find('.input-property').attr('name', 'ColumnMapping.Property.' + index).val(property);
			row.find('.input-column').attr('name', 'ColumnMapping.Column.' + index).val(column);
			row.find('.input-default').attr('name', 'ColumnMapping.Default.' + index);

			table.attr('data-maxindex', index);
			row.removeClass('column-mapping-new');

			row.find('.item-inner').removeClass('d-none');
			updatePropertyLabel(row.find('.mapping-property'), property);
			row.find('.mapping-column .left-label').text(column);

			row.find('.select-property').select2('destroy').remove();
			row.find('.select-column').select2('destroy').remove();

			row.find('.mapping-add').remove();
			row.find('.mapping-delete').show();

			appendNewMappingRow();
		});

        // Cancel editing.
        mappings.on('click', '.mapping-cancel', function (e) {
			e.stopPropagation();
			closeAllMappingEdits();
		});

        // Delete row.
        mappings.on('click', '.mapping-delete', function (e) {
			e.stopPropagation();
			$(this).closest('tr').remove();
		});

		// Close mapping edits.
		$(document).on('click', function (e) {
			var table = $(e.target).closest('table');

			if (table.length === 0 || !table.hasClass('column-mapping')) {
				closeAllMappingEdits();
			}
		});

		appendNewMappingRow();

		function closeAllMappingEdits() {
			$('#ImportColumnMappings').find('.mapping-edit').each(function () {
				var self = $(this);
				self.closest('.mapping-item').find('.item-inner').show();
				self.find('select').select2('destroy');
				self.remove();
			});
		}

		function updatePropertyLabel(context, val) {
			context.find('.right-label').text(val);

			var leftLabel = context.find('.left-label');
			var isLocalized = (val.indexOf(']', val.length - 1) !== -1);
			var text = context.find('select').find('option:selected').text();

			if (text.length > maxMappingLableLength) {
				leftLabel.text(text.substring(0, maxMappingLableLength) + '…');
				leftLabel.attr('title', $('<div/>').html(text).text());
			}
			else {
				leftLabel.text(text);
				leftLabel.attr('title', '');
			}

			context.find('i').removeClass('fa-globe fa-unlink').addClass(isLocalized ? 'fa-globe' : 'fa-unlink');
		}

		function initSelectBox(element, isProperty) {
			return element.select2({
				allowClear: !isProperty,
				minimumResultsForSearch: 16,
				containerCssClass: 'form-control',
				theme: 'bootstrap',
				placeholder: function () {
					$(this).data('placeholder');
				},
				matcher: function (params, data) {
					// If there are no search terms, return all of the data.
					if ($.trim(params.term) === '') {
						return data;
					}

					// Do not display the item if there is no 'text' property.
					if (typeof data.text === 'undefined') {
						return null;
					}
					var searchFor = params.term.toUpperCase();

					if (data.text.toUpperCase().indexOf(searchFor) > -1) {
						return data;
					}

					var val = $(data.element).val();
					if (val && val.toUpperCase().indexOf(searchFor) > -1) {
						return data;
					}

					return null;
				},
				escapeMarkup: function (m) {
					return m;
				},
				templateResult: (isProperty ? selectPropertyFormatting : selectColumnFormatting),
				templateSelection: (isProperty ? selectPropertyFormatting : selectColumnFormatting)
			});
		}

		function appendNewMappingRow() {
			var mappings = $('#ImportColumnMappings');
			if (!mappings.length)
				return;

			var html = $('#AddMappingTemplate').find('table tbody').html();

			mappings.find('table:first tbody').append(html);

			var row = mappings.find('table:first tr:last');

			initSelectBox(row.find('.select-property'), true);
			initSelectBox(row.find('.select-column'), false);
		}

		function selectPropertyFormatting(item, container) {
			try {
				if (item.text.length > 0) {
					var option = $(item.element);
					var isLocalized = item.id.indexOf(']', item.id.length - 1) !== -1;
					var html = '';

					if (option.length === 0) {
						html += '<div class="mapping-list-item">';
						html += '<span class="pr-2 d-inline-block">';
						html += '	<i class="fa fa-fw ' + (isLocalized ? 'fa-globe' : 'fa-unlink') + ' text-success"></i>';
						html += '</span>';
					}
					else {
						// Update mapped properties when first popup list item is about to be rendered.
						if (option.index() === 1) {
							mappedProperties = [];

							$('#ImportColumnMappings').find('input[name^="ColumnMapping.Property."]').each(function () {
								var value = $(this).val();
								if (!_.isEmpty(value)) {
									mappedProperties.push(value);
								}
							});
						}

						var mappingIndex = $.inArray(item.id, mappedProperties);

						html += '<div class="clear"></div>';
						html += '<div class="mapping-list-item' + (mappingIndex === -1 ? '' : ' muted') + '">';

						html += '<span class="pr-2 d-inline-block">';
						html += '<i class="fa fa-fw ';
						html += (isLocalized ? 'fa-globe' : (mappingIndex === -1 ? 'fa-unlink' : 'fa-link'));
						html += (mappingIndex === -1 ? ' text-success">' : ' text-warning">');
                        html += '</i></span>';
					}

					html += '<span class="ml-1 d-inline-block"';
					if (item.text.length > maxMappingLableLength) {
						html += ' title="' + $('<div/>').text(item.text).html() + '">' + item.text.substring(0, maxMappingLableLength) + '…';
					}
					else {
						html += '>' + item.text;
					}
					html += '</span>';

					html += '<span class="muted right-label ml-auto">' + item.id + '</span>';

					html += '</div>';
					return $(html);
				}
			}
			catch (e) { }

			return item.text;
		}

		function selectColumnFormatting(item, container) {
			try {
				if (item.id.length > 0) {
					var html = '';

					html += '<div class="mapping-list-item">';
					html += '<span>' + item.id + '</span>';

					if (item.text !== item.id) {
						html += '<span class="muted right-label ml-auto"'
						if (item.text.length > maxMappingLableLength) {
							html += ' title="' + $('<div/>').text(item.text).html() + '">' + item.text.substring(0, maxMappingLableLength) + '…';
						}
						else {
							html += '>' + item.text;
						}
						html += '</span>';
					}

					html += '</div>';
					return $(html);
				}
			}
			catch (e) { }

			return item.text;
		}
	});
</script>